import datetime

from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render,redirect,HttpResponse
from web import models

class tracer:
	def __init__(self):
		self.user_obj = None
		self.price_policy = None
		self.project = None

class LoginAuth(MiddlewareMixin):

	def process_request(self,request):

		current_path = request.path

		user_id = request.session.get('user_id')

		tracer_obj = tracer()
		request.tracer_obj = tracer_obj
		user_obj =  models.UserInfo.objects.filter(pk=user_id).first()
		request.tracer_obj.user_obj = user_obj

		# 白名单判断, 如果在白名单中放行
		if current_path in settings.WHITE_LIST:
			return

		if not user_id:
			return redirect('login')

		# 将当前用户的购买策略加到request对象中,方便后面使用
		# 1 策略数据要有
		# 用户绑定的是哪个策略

		tra_obj = models.Transaction.objects.filter(user=request.tracer_obj.user_obj, status=2, ).order_by(
			'-id').first()
		# 判断是否过期
		# 先看一下是不是免费版的,也就是结束时间为null,如果不是免费版的,拿出结束时间来看一下是不是过期了,如果过期了则报错
		end_datetime = tra_obj.end_datetime
		current_time = datetime.datetime.now()
		# 如果过期了
		if end_datetime and end_datetime < current_time:
			# 根据购买记录找到对应的策略,然后将策略保存到request对象中
			price_policy = models.PricePolicy.objects.filter(catogory=1,title='免费版').first()
			request.tracer_obj.price_policy = price_policy

		else:
			request.tracer_obj.price_policy = tra_obj.price_policy


	def process_view(self,request,view,args,kwargs):
		# args url无名分组匹配到的参数
		# kwargs url有名分组匹配到的参数
		if not request.path.startswith('/web/manage/'):
			return

		#print(view , args , kwargs)
		pro_id = kwargs.get('pro_id')

		# 我创建的
		project_obj = models.Project.objects.filter(id=pro_id,creator=request.tracer_obj.user_obj)
		if project_obj:
			request.tracer_obj.project = project_obj.first()
			return

		# 我参与的
		project_obj = models.ProjectUser.objects.filter(project_id=pro_id,user=request.tracer_obj.user_obj)
		if project_obj:
			request.tracer_obj.project = project_obj.first().project
			return

		return redirect('project_list')
		#view
		#<function dashboard at 0x000001F454E6B378> () {'pro_id': '4'}









